package com.fast.develop.api;

import com.fast.develop.core.ModuleContextFactory;
import com.fast.develop.core.enums.DdlAuto;
import com.fast.develop.core.io.ResourceManager;
import com.fast.develop.core.io.disk.DiskResourceManager;
import com.fast.develop.core.plugin.PluginRegister;
import com.fast.develop.meta.base.MetaConfiguration;
import com.fast.develop.meta.dm.MetaDomainRegistor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.sql.DataSource;
import java.io.UnsupportedEncodingException;
import java.util.List;


/**
 * @author 莫寅
 * 领域模型自动装配
 */
@Slf4j
public class FastDevelopApiAutoConfiguration {


    private DataSource dataSource;


    protected RequestMappingHandlerMapping requestMappingHandlerMapping;

    private DomainModelFastDevelopConfiguration fastDevelopConfiguration;


    /**
     * 请求拦截器
     */
    private final ObjectProvider<List<PluginRegister>> luginRegisterProvider;

    private ResourceManager resourceManager;

    private String resourcePath;


    @SneakyThrows
    public FastDevelopApiAutoConfiguration(
            DataSource dataSource,
            RequestMappingHandlerMapping requestMappingHandlerMapping,
            ObjectProvider<List<PluginRegister>> luginRegisterProvider
    ) {
        this.luginRegisterProvider = luginRegisterProvider;
        this.dataSource = dataSource;
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
        init();
    }



    @SneakyThrows
    private void init() {
        MetaConfiguration metaConfiguration = new MetaConfiguration();
        metaConfiguration.register(new MetaDomainRegistor());
        metaConfiguration.build();

        this.fastDevelopConfiguration = new DomainModelFastDevelopConfiguration(
                metaConfiguration,
                dataSource,
                requestMappingHandlerMapping,
                luginRegisterProvider
        );

        fastDevelopConfiguration
                .showSql(true)
                .ddlAuto(DdlAuto.UPDATE)
                .afterPropertiesSet();
    }


    @Bean
    public ModuleContextFactory moduleContextFactory(){
        return fastDevelopConfiguration.getModuleContextFactory();
    }


    public String getResourcePath() {
        return resourcePath;
    }

    @Bean
    public DomainModelFastDevelopConfiguration getFastDevelopConfiguration() {
        return fastDevelopConfiguration;
    }
}
